'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
const cors = require('cors')
// const baseUrl = 'https://easy-mock.com/mock/5ce73ac90edc0c38e2a1ad97'
// const baseUrl = 'http://192.168.100.115:9999'
const baseUrl = 'http://pre.mgr.s-gsun.com/'
// const baseUrl = 'http://192.168.100.111:9999'
const baseUrl2 = 'http://192.168.100.116:9999'
// const easyMock = ' http://192.168.37.247:7300/mock/5d908a358b666d051bdcefdb'
// const testUrl = 'http://192.168.100.121:9999'
const uploadUrl = 'http://192.168.100.111:9999'

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || 'vue Admin Template' // page title
// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
const port = 5003 // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: process.env.NODE_ENV === 'development' ? `//localhost:${port}` : `//${process.env.PKG_HOST}`,
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  // pages: {
  //   index: {
  //     // page 的入口
  //     entry: './src/index/main.js'
  //     // 模板来源
  //     // template: 'public/index.html',
  //     // // 在 dist/index.html 的输出
  //     // filename: 'index.html',
  //     // // 当使用 title 选项时，
  //     // // template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
  //     // title: 'Index Page',
  //     // // 在这个页面中包含的块，默认情况下会包含
  //     // // 提取出来的通用 chunk 和 vendor chunk。
  //     // chunks: ['chunk-vendors', 'chunk-common', 'index']
  //   }
  //   // 当使用只有入口的字符串格式时，
  //   // 模板会被推导为 `public/subpage.html`
  //   // 并且如果找不到的话，就回退到 `public/index.html`。
  //   // 输出文件名会被推导为 `subpage.html`。
  //   // subpage: 'src/subpage/main.js'
  // },
  devServer: {
    before(app, server) {
      app.use(cors())
    },

    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    // proxy: {
    //   // change xxx-api/login => mock/login
    //   // detail: https://cli.vuejs.org/config/#devserver-proxy
    //   [process.env.VUE_APP_BASE_API]: {
    //     target: `http://localhost:${port}/mock`,
    //     changeOrigin: true,
    //     pathRewrite: {
    //       ['^' + process.env.VUE_APP_BASE_API]: ''
    //     }
    //   }
    // },
    proxy: {
      '/auth': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/auth': '/auth'
        }
      },
      '/fs': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/fs': '/fs'
        }
      },
      '/admin': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/admin': '/admin'
        }
      },
      '/crm': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/crm': '/crm'
        }
      },
      '/distrition': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/distrition': '/distrition'
        }
      },
      '/projectdb': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/projectdb': '/projectdb'
        }
      },
      '/cd': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/cd': '/cd'
        }
      },
      '/ub': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/ub': '/ub'
        }
      },
      '/fs': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/fs': '/fs'
        }
      },
      '/mgr': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/mgr': '/mgr'
        }
      },
      '/contract': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/contract': '/contract'
        }
      },

      '/contract/contract': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/contract/contract': '/contract/contract'
        }
      },
      '/contract/public/crm-customer': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/contract/public/crm-customer': '/contract/public/crm-customer'
        }
      },
      '/contract/public/dept-list-dept-company': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/contract/public/dept-list-dept-company': '/contract/public/dept-list-dept-company'
        }
      },
      '/contract/public/dept-listAllCompanyLike': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/contract/public/dept-listAllCompanyLike': '/contract/public/dept-listAllCompanyLike'
        }
      },
      '/contract/public/get-unit': {
        target: baseUrl,
        changeOrigin: true,
        ws: false,
        secure: false,
        pathRewrite: {
          '^/contract/public/get-unit': '/contract/public/get-unit'
        }
      }
    }
    // after: require('./mock/mock-server.js')
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    externals: {
      vue: 'Vue',
      'element-ui': 'ELEMENT',
      'samples-ui': 'SAMPLES'
    }
  },
  chainWebpack(config) {
    const packageName = 'contract'
    config.output
      .library(packageName)
      .libraryTarget('umd')
      .jsonpFunction(`webpackJsonp_${packageName}`)
    // config.plugins.delete('preload') // TODO: need test
    // config.plugins.delete('prefetch') // TODO: need test

    const cdn = {
      css: [
        // element-ui css
        process.env.NODE_ENV === 'development' ? 'http://dev.static.s-gsun.com/libs/element/2.8.2/index.css' : `//${process.env.CDN_HOST}/libs/element/2.8.2/index.css`,
        // samples-ui css
        process.env.NODE_ENV === 'development' ? `http://dev.static.s-gsun.com/css/samples-ui@1.0.1.css` : `//${process.env.CDN_HOST}/css/samples-ui@1.0.1.css`
      ],
      js: [
        // vue must at first!
        process.env.NODE_ENV === 'development' ? 'http://dev.static.s-gsun.com/libs/vue/2.6.10/vue.js' : `//${process.env.CDN_HOST}/libs/vue/2.6.10/vue.min.js`,
        // element-ui js
        process.env.NODE_ENV === 'development' ? 'http://dev.static.s-gsun.com/libs/element/2.8.2/index.js' : `//${process.env.CDN_HOST}/libs/element/2.8.2/index.js`,
        // samples-ui js
        process.env.NODE_ENV === 'development' ? `http://dev.static.s-gsun.com/js/samples-ui@1.0.1.js` : `//${process.env.CDN_HOST}/js/samples-ui@1.0.1.js`
      ]
    }
    config.plugin('html')
      .tap(args => {
        args[0].cdn = cdn
        args[0].minify = false
        return args
      })

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    // config
    // https://webpack.js.org/configuration/devtool/#development
    /* .when(process.env.NODE_ENV === 'development',
        config => config.devtool('cheap-source-map')
      )*/

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          // config
          //   .plugin('ScriptExtHtmlWebpackPlugin')
          //   .after('html')
          //   .use('script-ext-html-webpack-plugin', [{
          //     // `runtime` must same as runtimeChunk name. default is `runtime`
          //     inline: /runtime\..*\.js$/
          //   }])
          //   .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          config.optimization.runtimeChunk('single')
        }
      )
  }
}
